import {
	defineStore
} from 'pinia'
import {
	navTo,
	setLoadingToast
} from '../../common/utils'
import {
	getInfo,
	getUserDetails,
	login,
	register
} from '../../api/logisitcsCompany'

const keyNames = 'LOGISTICE_COMPANY'

const useLogisicsCompany = defineStore(keyNames, {
	state: () => {
		return {
			// 物流登录成功后的信息
			userInfo: {},
			token: null
		}
	},

	getters: {
		getUserinfo: state => state.userInfo,
		getToken: state => state.token
	},

	actions: {
		// 存储userInfo 信息
		setUserinfo(payload) {
			this.userInfo = payload
		},
		setToken(token) {
			this.token = token
		},
		clear() {
			this.userInfo = {}
			this.token = ''
		},
		// 公司信息登录
		companyLogin(params) {
			let that = this
			try {
				setLoadingToast('正在登录...')
				login(params).then(res => {
					// console.log("res ============> ", res.data);
					that.setToken(res.data)
					that.getInfo()
				})
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		},
		// 获取详情
		getInfo() {
			let that = this
			try {
				getInfo().then(res => {
					console.log("res ========> ", res);
					that.getDetails(res.data.uId)
				})
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		},
		// 获取报车人详情
		getDetails(id) {
			let that = this
			try {
				getUserDetails(id).then(res => {
					setTimeout(() => {
						that.setUserinfo(res.data)
						uni.hideLoading()
						// 前往公司首页
						navTo("/pages/logisticsCompany/index/index")
					}, 200)
				})
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		},
		// 公司注册
		companyRegister(data) {
			// /
			let that = this
			try {
				setLoadingToast('正在提交...')
				register(data).then(res => {
					setTimeout(() => {
						uni.hideLoading()
						// true 注册成功
						if (res.data) {
							uni.showModal({
								title: '提交成功',
								content: '您的信息已提交成功，请耐心等待平台审核。',
								showCancel: false,
								cancelText: '',
								confirmText: '我知道了',
								success: res => {
									navTo("/pages/logisticsCompany/login/login")
								},
								fail: () => {},
								complete: () => {}
							});
						} else {
							// 注册失败
						}
					}, 200)
				})
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		}
	},
	// 数据持久化
	unistorage: true // 开启后对 state 的数据读写都将持久化
})

export default useLogisicsCompany